package com.example.musicplayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.util.EncodingUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class LrcService {

	private static final int DOWNLOAD_COMPLETE = 1455;
	private static final int READ_FILE = 4646;
	private static final int DOWNLOADINNG = 4865;
	private static final int DOWNLOAD_FAILED = 14684;
	private static final int READ_IMAGE = 41654;
	private static final int READ_IMG_FAILED = 4879;
	String lrcContent = "";
	String[] lrcStrings;
	String[] timeStrings;
	File basePath = null;
	Bitmap bitmap = null;
	Handler handler;
	String musicName = "";
	String albumDrectory = "/MusicPlayer/albums/";
	List<Map<String, String>> lrcList = new ArrayList<Map<String, String>>();

	public LrcService(String path, String file, String author, Handler handler)
			throws Exception {
		// TODO Auto-generated constructor stub
		this.handler = handler;
		musicName = file.replace(".lrc", "");
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			basePath = Environment.getExternalStorageDirectory();
		}
		lrcContent = readFile(path, file, author, handler);
		bitmap = readImage(Environment.getExternalStorageDirectory()
				+ albumDrectory, file.replace(".lrc", ".jpg"), author, handler);
	}

	public Bitmap readImage(String path, String file, String author,
			Handler handler) {
		// TODO Auto-generated method stub
		Log.i("readImg", path + file);
		Bitmap bitmap;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		File file2 = new File(path, file);
		if (file2.exists()) {
			bitmap = BitmapFactory.decodeFile(path + file);
			if (bitmap != null) {
				handler.sendEmptyMessage(READ_IMAGE);
				Log.i("img", bitmap.toString());
			} else {
				handler.sendEmptyMessage(READ_IMG_FAILED);
			}
			return bitmap;
		} else {
			downLoadImg(file.replace(".jpg", ""), author, handler);
		}
		return null;
	}

	private void downLoadImg(final String replace, final String author,
			final Handler handler) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					JasonParse jasonParse = new JasonParse(replace, author,
							handler);
					jasonParse.downLoadAlbum(handler);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	public String getLrcContent() {
		return lrcContent;
	}

	public List<Map<String, String>> getLrcList() {

		if (lrcContent == null) {
		} else if (lrcContent.contains("[00:")) {
			lrcStrings = lrcContent.split("\n");
			Map<String, String> map = new HashMap<String, String>();
			String timeString = "";
			String lString = "";
			for (int i = 0; i < lrcStrings.length; i++) {
				String[] string = lrcStrings[i].split("]");
				for (int j = 0; j < string.length - 1; j++) {
					if (string[j].length() > 1 && string[j].charAt(1) >= '0'
							|| string[j].charAt(1) <= '9') {
						String s = "";
						for (int k = 1; k <= 5 && k < string[j].length(); k++) {
							s += string[j].charAt(k);
						}
						map.put(s, string[string.length - 1]);
						timeString += s + "\n";
						lString += string[string.length - 1] + "\n";
					}
				}
			}
			lrcList.add(map);
			lrcStrings = lString.split("\n");
			timeStrings = timeString.split("\n");
			for (int i = 0; i < lrcList.size(); i++) {
			}
		} else {
			Message message = new Message();
			message.what = DOWNLOAD_FAILED;
			message.obj = musicName;
			handler.sendMessage(message);
		}

		return lrcList;
	}

	public String[] getLrcStrings() {
		return lrcStrings;
	}

	public String[] getTimeStrings() {
		return timeStrings;

	}

	String readFile(String path, String filename, String author, Handler handler)
			throws Exception {
		FileInputStream fileInputStream = null;
		String temp = "";
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			File file = new File(path, filename);
			if (file.exists()) {
				try {
					fileInputStream = new FileInputStream(file);
					int len = 0;
					try {
						len = fileInputStream.available();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					byte[] buffer = new byte[len];
					try {
						fileInputStream.read(buffer);
						temp = EncodingUtils.getString(buffer, "utf-8");
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					try {
						if (fileInputStream != null) {
							fileInputStream.close();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else {
				downLoadLrc(filename.replace(".lrc", ""), author, handler);
				Message message = new Message();
				message.what = DOWNLOADINNG;
				message.obj = filename;
				handler.sendMessage(message);
				temp = null;
			}
		}
		return temp;
	}

	public void downLoadLrc(final String lrcUrl, final String author,
			final Handler handler) throws Exception {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					JasonParse jasonParse = new JasonParse(lrcUrl, author,
							handler);
					jasonParse.downLoadLrc(handler);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}
}
